using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Universal.Application.Contracts.Jwt;
using Universal.Application.Contracts.Storage;
using Universal.Domain.Events;
using Universal.Domain.Repositories;
using Universal.Infrastructure.DB;
using Universal.Infrastructure.Events;
using Universal.Infrastructure.Jwt;
using Universal.Infrastructure.Repositories;
using Universal.Infrastructure.Storage;

namespace Universal.Infrastructure;

/// <summary>
/// 扩展方法，用于在 Program.cs 里注册所有基础设施服务
/// </summary>
public static class ServiceCollectionExtension
{

    public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
    {
        // 在这里注册基础设施服务

        // 注册数据库上下文
        var connectionString = configuration.GetConnectionString("pgsql");
        services.AddDbContext<AppDbContext>(options =>
       options.UseNpgsql(configuration.GetConnectionString("pgsql")));

        // 注册通用仓储
        services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));

        // 注册文件仓储
        services.AddScoped<IFileRepository, FileRepository>();

        // 注册JwtToken服务
        services.AddScoped<IJwtTokenService, JwtTokenService>();

        // 注册领域事件处理器
        services.AddMediatR(cfg =>
        {
            cfg.RegisterServicesFromAssemblyContaining<MediatRDomainEventDispatcher>();
        });

        // 注册领域事件分发器
        services.AddScoped<IDomainEventDispatcher, MediatRDomainEventDispatcher>();

        // 注册文件存储
        services.AddScoped<IFileStorage, LocalFileStorage>();

        return services;
    }
}